package com.bookcity.controller;

import com.bookcity.enums.UserPermission;
import com.bookcity.pojo.User;
import com.bookcity.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@Controller
@RequestMapping("/userSL")
public class ProUsersSLController {

    @Autowired
    @Qualifier("userServiceImpl")
    private UserService usersService;

    public int getUid(HttpServletRequest req){
        int uid = 0;
        Cookie[] cookies = req.getCookies();
        for (Cookie item : cookies){
            if (item.getName().equals("uid")){
                uid = Integer.parseInt(item.getValue().trim());
            }
        }
        return uid;
    }

    //  上传头像
    @ResponseBody
    @RequestMapping("/uploadAva")
    public String OnloadUserAva(@RequestParam("avatar") CommonsMultipartFile avatar, HttpServletRequest req) throws IOException {
        int uid = getUid(req);
        String path = req.getServletContext().getRealPath("/static/avatars/"+uid);
        File realPath = new File(path);
        //  判断目录是否存在, 不存在则创建目录
        if (!realPath.exists()) {
            realPath.mkdir();
        }
        String thePicPath = realPath + "/" + avatar.getOriginalFilename();
        avatar.transferTo(new File(thePicPath));
        User users = usersService.queryUsers(uid);
        users.setUavatar(thePicPath);
        usersService.updateUsers(users);

        System.out.println("Save Path: " + thePicPath);
        return thePicPath; //  修改后应大于0
    }

    //  修改昵称、性别、邮箱、个性签名
    @ResponseBody
    @RequestMapping("/updateUser")
    public boolean OnloadUserNGS(@RequestParam("uid") String uid,
                                 @RequestParam("uname") String name ,    @RequestParam("urole") String role,
                                 @RequestParam("signature") String sig , @RequestParam("upasswd") String passwd,
                                 @RequestParam("uemail") String email,   @RequestParam("uphone") String phone,
                                 HttpServletRequest req){
//        int uid = getUid(req);
        User users = usersService.queryUsers(Integer.parseInt(uid));
        if(users == null)
            return false;
        users.setUname(name);
        users.setRole(UserPermission.valueOf(role).getCode());
        users.setSignatrue(sig);
        users.setUpass(passwd);
        users.setUemail(email);
        users.setContactphone(phone);
        return  usersService.updateUsers(users)>0;   //  修改大于0代表成功
    }

    //  显示账号、修改密码、手机号
    @ResponseBody
    @RequestMapping("/uploadAPP")
    public boolean OnloadAPP(@RequestParam("password") String password , @RequestParam("phone")String phone , HttpServletRequest req , Model model){
        int uid = getUid(req);
        model.addAttribute("uid", uid); //  这是给info.jsp中账号信息中的账号input只读显示的
        User users = usersService.queryUsers(uid);
        users.setUpass(password);
        users.setContactphone(phone);
        return usersService.updateUsers(users)>0;
    }

    //  下载文件示例
    @ResponseBody
    @RequestMapping("/download")
    public String DownloadUserInfo(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String path = request.getServletContext().getRealPath("/static/avatars");
        String fileName = "Rose.jpg";
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
        File file = new File(path, fileName);
        InputStream input = new FileInputStream(file);
        OutputStream out = response.getOutputStream();
        byte[] buff = new byte[1024];

        int index = -1;
        while((index = input.read(buff)) != -1) {
            out.write(buff, 0, index);
            out.flush();
        }

        out.close();
        input.close();
        return null;
    }

}
